package com.erpanderp.wam.tm.view;

import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.context.RequestContext;
import com.erpanderp.wam.tm.model.entity.Band;
import com.erpanderp.wam.tm.model.entity.RRFManagerRecommendation;
import com.erpanderp.wam.tm.model.entity.RecruitmentProfile;
import com.erpanderp.wam.tm.model.entity.RecruitmentRequest;
import com.erpanderp.wam.tm.model.entity.SkillRating;
import com.erpanderp.wam.tm.model.service.BandDAO;
import com.erpanderp.wam.tm.model.service.RRFDAO;
import com.erpanderp.wam.tm.model.service.RRFManagerRecommendationDAO;
import com.erpanderp.wam.tm.model.service.RecruitmentProfileDAO;
import com.erpanderp.wam.tm.model.service.SkillRatingDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.ValidationUtil;

@ManagedBean
@ViewScoped
public class ViewFeedBackBean implements Serializable{

	private static final long serialVersionUID = 1L;
	HttpServletRequest request = (HttpServletRequest) FacesContext
			.getCurrentInstance().getExternalContext().getRequest();
	private Map<String,String> proceedWithBuyoutMap = CommonLookup.getAuthenticationsMap();
	
	private String rrfCode;
	private String candidateEmail;
	private float percntHickExpected;
	private float erpOfferLPA;
	private long selectedBandId;
	private boolean FORM_VALID;
	private boolean disableManagerRecommendation;
	private String activity;
	
	private RecruitmentProfile recruitmentProfile = new RecruitmentProfile();
	private RecruitmentRequest recruitmentRequest = new RecruitmentRequest();
	private RRFManagerRecommendation rrfManagerRecommendation=new RRFManagerRecommendation();
	private Band band=new Band();
	
	private RecruitmentProfileDAO recruitmentProfileDAO = new RecruitmentProfileDAO();
	private SkillRatingDAO skillRatingDAO = new SkillRatingDAO();
	private RRFDAO rrfDAO = new RRFDAO();
	private RRFManagerRecommendationDAO rrfManagerRecommendationDAO=new RRFManagerRecommendationDAO();
	private BandDAO bandDAO = new BandDAO();
	
	private List<SkillRating> skillRatingsSingleLevel = new ArrayList<SkillRating>();
	private List<SkillRating> skillRatingsTwoLevel = new ArrayList<SkillRating>();
	private List<Band> bands = new ArrayList<Band>();
	private Map<String, Long> bandsMap = new HashMap<String, Long>();
	
	private Date dateAfterFourMnths;

	public ViewFeedBackBean() {
		
		rrfCode=request.getParameter("rrfCode");
		candidateEmail=request.getParameter("candidateEmail");
		activity = request.getParameter("activity");
		
		recruitmentRequest = rrfDAO.getRRFByRecruitmentRequestCode(rrfCode);
		recruitmentProfile=recruitmentProfileDAO.getRecruitmentProfileByCandidateEmail(candidateEmail);	
		
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat formate= new SimpleDateFormat("dd/MM/yyyy");

		currentDate.setTime(recruitmentRequest.getRequestDate());
		
		//get after four months
		currentDate.add(Calendar.MONTH,4);
		try{
			dateAfterFourMnths = (Date)formate.parse(formate.format(currentDate.getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		} 
		
		if(recruitmentProfile.getManagerRecommendationStatus().equalsIgnoreCase("Available")){
			setDisableManagerRecommendation(true);
		}		
		
		skillRatingsSingleLevel=skillRatingDAO.getSkillRatings(rrfCode,recruitmentProfile.getRecruitmentProfileId(),"Single Level");
		
		if(recruitmentRequest.getInterviewLevel().equalsIgnoreCase("Two Level")){
			skillRatingsTwoLevel=skillRatingDAO.getSkillRatings(rrfCode,recruitmentProfile.getRecruitmentProfileId(),"Two Level");
		}
		
		float ectc = recruitmentProfile.getEctc();
		float ctc = recruitmentProfile.getCtc();
		
		percntHickExpected = ((ectc-ctc) /ctc)*100 ;
		
		float newPercntHickExpected = (float) (Math.round(percntHickExpected*100.0)/100.0);
		
		System.out.println("rrfManagerRecommendation==============="+rrfManagerRecommendation);
		System.out.println("newPercntHickExpected==============="+newPercntHickExpected);
		
		rrfManagerRecommendation.setPercentHikeExpected(newPercntHickExpected);
		
		
		
		if(activity.equals("approvedByHigherAuthority") || activity.equals("releaseOfferLetter")){
			
			rrfManagerRecommendation=rrfManagerRecommendationDAO.getRRFManagerRecomendationsByRRFCode(rrfCode,recruitmentProfile.getRecruitmentProfileId());
			
		}		
	}
	
	
	public void createManagerRecommendationListener(ActionEvent e){
		System.out.println("Listener...");
		
		bands = rrfDAO.getAllBands();
		for (Band band : bands) {
			bandsMap.put(band.getBand(), band.getBandId());
		}
		
	}
	
	//CREATE MANAGER RECOMMENDATION ACTION
	public String managerRecommendationAction(){
		 System.out.println("INSIDE MANAGER Recommendation METHOD:::::");
			
		 validateMangerRecommendations();
			
			if(FORM_VALID){
				System.out.println("===============111111111111==============");
				band=bandDAO.getBandByBandId(selectedBandId);
				rrfManagerRecommendation.setBand(band);
				rrfManagerRecommendation.setRecruitmentRequestCode(rrfCode);
				rrfManagerRecommendation.setRecruitmentProfile(recruitmentProfile);
				System.out.println("===============2222222222==============");
				rrfManagerRecommendation.setCreateDate(new Date());
				rrfManagerRecommendation.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
				rrfManagerRecommendation.setStatus(CommonLookup.STATUS_ACTIVE);
				System.out.println("===============3333333333333333==============");
				rrfManagerRecommendationDAO.createManagerRecommendation(rrfManagerRecommendation);	
				System.out.println("===============444444444==============");
				recruitmentProfile.setBand(band);
				recruitmentProfile.setManagerRecommendationStatus("Available");
				recruitmentProfileDAO.saveRecruitmentProfile(recruitmentProfile);
				System.out.println("===============45555555555555==============");
				
				FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO," Your are submitted successfully.", ""));
				
				Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

				  String rrfCode = params.get("rrfCode");
				  String activity=params.get("activity");	
				  
				  FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("rrfCode", rrfCode);		  
				  FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("activity", activity);
				
				  try {
					FacesContext.getCurrentInstance().getExternalContext().redirect("/wam/tm/scheduleinterviews.html?rrfCode="+rrfCode+"&activity="+activity);
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			//	RequestContext.getCurrentInstance().execute("recommendationDialog.hide();");
				return "viewfeedback";
			}else{
				RequestContext.getCurrentInstance().execute("recommendationDialog.show();");	
				return null;
			}
			
		}
	
    //CLOSE DIALOG BOX
	public void dialogClose(ActionEvent e){
		//travelRequests.set(travelRequests.indexOf(travelRequest), travelRequestDAO.getTravelRequestById(travelRequest.getTravelRequestId()));
		RequestContext.getCurrentInstance().execute("recommendationDialog.hide()");		
	}
	
	//GET % Values	
	public void getERPOfferHike(AjaxBehaviorEvent e){
		
//		//float erpOfferPercnt;	
//		erpOfferLPA=rrfManagerRecommendation.getErpOfferPriceLPA();
//		//erpOfferPercnt = 	((erpOfferLPA-recruitmentProfile.getCtc())/recruitmentProfile.getCtc())*100;
//		rrfManagerRecommendation.setErpOfferedHikePercent(((erpOfferLPA-recruitmentProfile.getCtc())/recruitmentProfile.getCtc())*100);
		
		float erpOfferPercnt;
		erpOfferLPA=rrfManagerRecommendation.getErpOfferPriceLPA();
		erpOfferPercnt = ((erpOfferLPA-recruitmentProfile.getCtc())/recruitmentProfile.getCtc())*100;
		System.out.println("=======Before====111111111=erpOfferPercnt==="+erpOfferPercnt);
		float newErpOfferPercnt = (float) (Math.round(erpOfferPercnt*100.0)/100.0);
		rrfManagerRecommendation.setErpOfferedHikePercent(newErpOfferPercnt);
		
	}
	
	//Validations
	 
	 public void validateMangerRecommendations(){
		 System.out.println("=======Inside =====validateMangerRecommendations()======START===");
			FORM_VALID=true;		
			
			
			if(Integer.toString(rrfManagerRecommendation.getErpOfferPriceLPA()).length() > 1){
				if (ValidationUtil.isSalaryValid(Integer.toString(rrfManagerRecommendation.getErpOfferPriceLPA()), "ERPandERP Offer(Per Annum)", null,
						FacesContext.getCurrentInstance()) != null) {
					FORM_VALID = false;
				} 
			}
			if (ValidationUtil.isEmpty(Integer.toString(recruitmentProfile.getCandidateNoticePeriod()), "Notice Period (Days)",
					null, FacesContext.getCurrentInstance()) != null) {
				FORM_VALID = false;
			}else{
				if(recruitmentProfile.getCandidateNoticePeriod() < 0){
					FORM_VALID = false;
					FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Notice Period should be grater than zero.", ""));
					recruitmentProfile.setCandidateNoticePeriod(0);
				}	
			}
			
			if(ValidationUtil.isEmpty(rrfManagerRecommendation.getManagerRecommendation(), "Final Recommendation", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID=false;
			}
			if(ValidationUtil.isEmpty(rrfManagerRecommendation.getManagerRemarks(), "Final Remarks", null, FacesContext.getCurrentInstance()) != null){
				FORM_VALID=false;
			}
			
			if(ValidationUtil.isEmpty((recruitmentProfile.getExpectedJoiningDate() !=null) ? recruitmentProfile.getExpectedJoiningDate().toString():null, "Expected Joining Date", null, FacesContext.getCurrentInstance()) != null){
				
				   FORM_VALID = false;
			} 
			if(recruitmentProfile.getExpectedJoiningDate() != null){
				   if(recruitmentProfile.getExpectedJoiningDate().before(recruitmentRequest.getRequestDate())){
					   FORM_VALID = false;
					   FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Expected date of joining should be greater than rrf create date", ""));
				   }
				   if(recruitmentProfile.getExpectedJoiningDate().after(dateAfterFourMnths)){
					   FORM_VALID = false;
					   FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Expected date of joining should not be exceed 4 months", ""));
				   }
			}
			
			System.out.println("=Inside =====validateMangerRecommendations()== END========="+FORM_VALID);
	 }

	//SETTER AND GETTER METHODS
	public String getRrfCode() {
		return rrfCode;
	}

	public void setRrfCode(String rrfCode) {
		this.rrfCode = rrfCode;
	}

	public String getCandidateEmail() {
		return candidateEmail;
	}

	public void setCandidateEmail(String candidateEmail) {
		this.candidateEmail = candidateEmail;
	}

	public RecruitmentProfile getRecruitmentProfile() {
		return recruitmentProfile;
	}

	public void setRecruitmentProfile(RecruitmentProfile recruitmentProfile) {
		this.recruitmentProfile = recruitmentProfile;
	}

	public RecruitmentProfileDAO getRecruitmentProfileDAO() {
		return recruitmentProfileDAO;
	}

	public void setRecruitmentProfileDAO(RecruitmentProfileDAO recruitmentProfileDAO) {
		this.recruitmentProfileDAO = recruitmentProfileDAO;
	}

	public SkillRatingDAO getSkillRatingDAO() {
		return skillRatingDAO;
	}

	public void setSkillRatingDAO(SkillRatingDAO skillRatingDAO) {
		this.skillRatingDAO = skillRatingDAO;
	}


	public RRFDAO getRrfDAO() {
		return rrfDAO;
	}


	public void setRrfDAO(RRFDAO rrfDAO) {
		this.rrfDAO = rrfDAO;
	}


	public List<Band> getBands() {
		return bands;
	}


	public void setBands(List<Band> bands) {
		this.bands = bands;
	}


	public Map<String, Long> getBandsMap() {
		return bandsMap;
	}


	public void setBandsMap(Map<String, Long> bandsMap) {
		this.bandsMap = bandsMap;
	}


	public RRFManagerRecommendation getRrfManagerRecommendation() {
		return rrfManagerRecommendation;
	}


	public void setRrfManagerRecommendation(RRFManagerRecommendation rrfManagerRecommendation) {
		this.rrfManagerRecommendation = rrfManagerRecommendation;
	}


	public RRFManagerRecommendationDAO getRrfManagerRecommendationDAO() {
		return rrfManagerRecommendationDAO;
	}


	public void setRrfManagerRecommendationDAO(
			RRFManagerRecommendationDAO rrfManagerRecommendationDAO) {
		this.rrfManagerRecommendationDAO = rrfManagerRecommendationDAO;
	}


	public Map<String,String> getProceedWithBuyoutMap() {
		return proceedWithBuyoutMap;
	}


	public void setProceedWithBuyoutMap(Map<String,String> proceedWithBuyoutMap) {
		this.proceedWithBuyoutMap = proceedWithBuyoutMap;
	}


	public float getPercntHickExpected() {
		return percntHickExpected;
	}


	public void setPercntHickExpected(float percntHickExpected) {
		this.percntHickExpected = percntHickExpected;
	}


	public float getErpOfferLPA() {
		return erpOfferLPA;
	}


	public void setErpOfferLPA(float erpOfferLPA) {
		this.erpOfferLPA = erpOfferLPA;
	}


	public long getSelectedBandId() {
		return selectedBandId;
	}


	public void setSelectedBandId(long selectedBandId) {
		this.selectedBandId = selectedBandId;
	}


	public BandDAO getBandDAO() {
		return bandDAO;
	}


	public void setBandDAO(BandDAO bandDAO) {
		this.bandDAO = bandDAO;
	}


	public Band getBand() {
		return band;
	}


	public void setBand(Band band) {
		this.band = band;
	}


	public String getActivity() {
		return activity;
	}


	public void setActivity(String activity) {
		this.activity = activity;
	}


	public boolean isDisableManagerRecommendation() {
		return disableManagerRecommendation;
	}


	public void setDisableManagerRecommendation(boolean disableManagerRecommendation) {
		this.disableManagerRecommendation = disableManagerRecommendation;
	}


	public RecruitmentRequest getRecruitmentRequest() {
		return recruitmentRequest;
	}


	public void setRecruitmentRequest(RecruitmentRequest recruitmentRequest) {
		this.recruitmentRequest = recruitmentRequest;
	}


	public List<SkillRating> getSkillRatingsTwoLevel() {
		return skillRatingsTwoLevel;
	}


	public void setSkillRatingsTwoLevel(List<SkillRating> skillRatingsTwoLevel) {
		this.skillRatingsTwoLevel = skillRatingsTwoLevel;
	}


	public List<SkillRating> getSkillRatingsSingleLevel() {
		return skillRatingsSingleLevel;
	}


	public void setSkillRatingsSingleLevel(List<SkillRating> skillRatingsSingleLevel) {
		this.skillRatingsSingleLevel = skillRatingsSingleLevel;
	}

}
